﻿using UnityEngine;
namespace JH
{
    /// <summary>
    /// 复制纹理到一个新的无压缩纹理上
    /// </summary>
    public static class DuplicateTexture2DExtension
    {
        /// <summary>
        ///  复制纹理到一个新的无压缩纹理上
        /// </summary>
        public static Texture2D CreateTextureFromEm(this Texture2D source)
        {
            // 创建一个新的Texture2D对象，其中的格式设置为RGBA32，这是一个非压缩格式
            Texture2D copy = new Texture2D(source.width, source.height,
                TextureFormat.RGBA32, false);

            // 将当前RenderTexture激活为全局的RenderTexture
            RenderTexture activeRenderTexture = RenderTexture.active;
            // 创建一个临时的RenderTexture对象
            RenderTexture tempRenderTexture = RenderTexture.GetTemporary(source.width, source.height);

            // 将源Texture复制到临时RenderTexture
            Graphics.Blit(source, tempRenderTexture);
           
            // 将临时RenderTexture设置为当前的RenderTexture
            RenderTexture.active = tempRenderTexture;
          
            // 将RenderTexture中的像素信息复制到新的Texture2D对象中
            copy.ReadPixels(new Rect(0, 0, tempRenderTexture.width, tempRenderTexture.height), 0, 0);
            copy.Apply();

            // 重置RenderTexture设置
            RenderTexture.active = activeRenderTexture;
            RenderTexture.ReleaseTemporary(tempRenderTexture);

            return copy;
        }
    }
}